import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_yres/tool/Constant.dart';
import 'address_entity.dart';
import 'addAddress.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
class MyAddressPage extends StatefulWidget {
  int type = 0;
  MyAddressPage({Key key, this.type}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyAddressView();
  }
}

class MyAddressView extends State<MyAddressPage> {
  List<AddressListDataData> dataList = new List();
  int page = 1;
  String token = "";
  String name = "";
  EasyRefreshController _controller = EasyRefreshController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      print(TOKEN);
      token = value;
      print(token);
      loadList();
    });
  }

  loadList() async {
     FormData data =
        new FormData.fromMap({'token': token});
    print(data);
    Response<String> response =
        await HttpUtil().post(Api.AddressListUrl, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    if (mounted) if (page == 1) {
      _controller.finishRefresh();
    } else {
      _controller.finishLoad();
    }
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    AddressListEntity homeListEntity = new AddressListEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (page == 1) {
          dataList.clear();
          dataList.addAll(homeListEntity.data.datas);
        } else {
          dataList.addAll(homeListEntity.data.datas);
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
      appBar: new AppBar(
        title: Text(widget.type == 0 ? '我的地址' : '选择地址',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
        actions: <Widget>[
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.fromLTRB(0, 0, 13, 0),
              child: Text(
                '添加',
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                    color: mainColor),
              ),
            ),
            onTap: () {
              Navigator.of(context)
                  .push<String>(MaterialPageRoute(builder: (context) {
                return new AddAddressPage();
              })).then((value) {
                if (value != null) {
                  page = 1;
                  loadList();
                }
              });
            },
          )
        ],
      ),
      body: new Container(
          color: divideColor,
          child: Column(
            children: <Widget>[
              // Container(
              //   padding: EdgeInsets.all(10),
              //   color: f0Color,
              //   child: Row(
              //     children: <Widget>[
              //       Expanded(
              //         flex: 1,
              //         child: Container(
              //           margin: EdgeInsets.fromLTRB(
              //               ScreenUtil.getInstance().setHeight(DP_10),
              //               0,
              //               ScreenUtil.getInstance().setHeight(DP_10),
              //               0),
              //           height: ScreenUtil.getInstance().setHeight(DP_60),
              //           decoration: BoxDecoration(
              //               color: white,
              //               borderRadius: BorderRadius.circular(20.0)),
              //           child: ConstrainedBox(
              //             constraints: BoxConstraints(maxHeight: DP_80),
              //             child: TextField(
              //               keyboardAppearance: Brightness.light,
              //               maxLines: 1,
              //               onChanged: (value) {
              //                 name = value;
              //               },
              //               cursorColor: mainColor,
              //               decoration: new InputDecoration(
              //                   // contentPadding: EdgeInsets.all(0),
              //                   prefixIcon: Icon(
              //                     Icons.search,
              //                     color: Colors.black45,
              //                   ),
              //                   hintText: "姓名、手机号",
              //                   border: InputBorder.none,
              //                   hintStyle: TextStyle(
              //                       color: Colors.black45,
              //                       fontSize: ScreenUtil.getInstance()
              //                           .setSp(NORMAL_FONT_SIZE))),
              //             ),
              //           ),
              //         ),
              //       ),
              //       GestureDetector(
              //         behavior: HitTestBehavior.opaque,
              //         child: Container(
              //             alignment: Alignment.center,
              //             width: ScreenUtil.getInstance().setWidth(DP_80),
              //             child: Text('搜索',
              //                 style: TextStyle(
              //                     color: black_99,
              //                     fontSize: ScreenUtil.getInstance()
              //                         .setSp(NORMAL_FONT_SIZE)))),
              //         onTap: () {
              //           page = 1;
              //           loadList();
              //         },
              //       )
              //     ],
              //   ),
              // ),
              Expanded(
                child: new EasyRefresh(
                  enableControlFinishRefresh: true,
                  enableControlFinishLoad: true,
                  header: MaterialHeader(),
                  footer: MaterialFooter(),
                  controller: _controller,
                  child: ListView.separated(
                      itemBuilder: _renderRow,
                      separatorBuilder: (BuildContext context, int index) {
                        return Container(
                          color: divideColor,
                          height: 1,
                        );
                      },
                      itemCount: dataList.length),
                  onRefresh: () async {
                    page = 1;
                    loadList();
                  },
                  onLoad: () async {
                    page++;
                    loadList();
                  },
                ),
              ),
              new Container(
                width: double.infinity,
                margin:
                    EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_60)),
                height: ScreenUtil.getInstance().setHeight(DP_80),
                decoration: new BoxDecoration(
                    color: mainColor,
                    borderRadius: BorderRadius.circular(10.0)),
                child: new FlatButton(
                  child: new Padding(
                    padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                    child: new Text(
                      "添加新地址",
                      style: new TextStyle(
                          color: Colors.white,
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                    ),
                  ),
                  onPressed: () {
                    Navigator.of(context)
                        .push<String>(MaterialPageRoute(builder: (context) {
                      return new AddAddressPage();
                    })).then((value) {
                      if (value != null) {
                        page = 1;
                        loadList();
                      }
                    });
                  },
                ),
              )
            ],
          )),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      child: new Container(
        color: Colors.white,
        padding: EdgeInsets.all(15.0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            new Row(
              children: <Widget>[
                Text(
                  dataList[index].consignee == null
                      ? ""
                      : dataList[index].consignee,
                  style: TextStyle(
                      fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                      color: Colors.black),
                ),
                Container(
                  width: DP_10,
                ),
                Expanded(
                  flex: 3,
                  child: Text(
                    dataList[index].contact_number,
                    style: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                        color: Colors.black87),
                  ),
                )
              ],
            ),
            Container(
              padding: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(DP_10), 0, 0),
              child: Text(
                dataList[index].province +
                    dataList[index].city +
                    dataList[index].county +
                    dataList[index].detail_address,
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                    color: Colors.black87),
              ),
            ),
            new Container(
              child: new Row(
                children: <Widget>[
                  Checkbox(
                      value: dataList[index].is_default == 'Y',
                      activeColor: mainColor,
                      checkColor: black_99,
                      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      onChanged: (bool x) {
                        dataList[index].is_default =
                            (dataList[index].is_default == 'Y' ? 'N' : 'Y');
                        change(index);

                        setState(() {});
                      }),
                  Text('默认地址',
                      style: TextStyle(
                          color: Colors.black54,
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),
                  Expanded(
                    child: Text(''),
                  ),
                  new GestureDetector(
                    onTap: () {
                      deleteAddress(context, index);
                    },
                    child: new Container(
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_20),
                          2,
                          ScreenUtil.getInstance().setHeight(DP_20),
                          2),
                      decoration: new BoxDecoration(
                          borderRadius: BorderRadius.circular(5.0),
                          border:
                              Border.all(color: Colors.black54, width: 1.0)),
                      child: Text(
                        '删除',
                        style: TextStyle(
                            fontSize:
                                ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                            color: Colors.black54),
                      ),
                    ),
                  ),
                  new GestureDetector(
                    onTap: () {
                      Navigator.of(context)
                          .push<String>(MaterialPageRoute(builder: (context) {
                        return new AddAddressPage(item: dataList[index]);
                      })).then((value) {
                        if (value != null) {
                          page = 1;
                          loadList();
                        }
                      });
                    },
                    child: new Container(
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_20),
                          2,
                          ScreenUtil.getInstance().setHeight(DP_20),
                          2),
                      margin: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_20), 0, 0, 0),
                      decoration: new BoxDecoration(
                          borderRadius: BorderRadius.circular(5.0),
                          border: Border.all(color: mainColor, width: 1.0)),
                      child: Text(
                        '编辑',
                        style: TextStyle(
                            fontSize:
                                ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                            color: mainColor),
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
      onTap: () {
        if (widget.type == 1) {
          Navigator.of(context).pop(dataList[index]);
        }
      },
    );
  }

  change(int index) async {
    
    Map map = new Map();
    map['token'] = token;
    map['address_id'] = dataList[index].id;
    map['province'] = dataList[index].province;
    map['city'] = dataList[index].city;
    map['county'] = dataList[index].county;
    map['detail_address'] = dataList[index].detail_address;
    map['consignee'] = dataList[index].consignee;
    map['contact_number'] = dataList[index].contact_number;
    map['is_default'] = dataList[index].is_default == 'N' ? "N" : "Y";
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.EditAddresstUrl, data: data);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    // Navigator.of(context).pop(1);
    // print(userMap['data'].toString());
    if (code == 1 && mounted) {
      page = 1;
      loadList();
    } else {
      Fluttertoast.showToast(msg: msg);
    }
  }

  deleteAddress(BuildContext context, int index) {
    showDialog(
      context: context,
      builder: (context) => new AlertDialog(
        title: new Text('提示'),
        content: new Text('确定删除该收货地址吗，删除后不可撤回'),
        actions: <Widget>[
          new FlatButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: new Text(
              '取消',
              style: TextStyle(color: Colors.grey),
            ),
          ),
          new FlatButton(
            onPressed: () {
              del(index);
              Navigator.of(context).pop(false);
            },
            child: new Text('确定删除', style: TextStyle(color: mainColor)),
          ),
        ],
      ),
    );
  }

  del(int index) async {
    Map map = new Map();
    map['token'] = token;
    map['address_id'] = dataList[index].id;
    // map['sign_type'] = SignType.DELETE_ADDRESS;
    print(map);
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.DelAddressUrl, data: data);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    // print(userMap['data'].toString());
    if (code == 1 && mounted) {
      dataList.removeAt(index);
      setState(() {});
    }
  }
}
